package com.ruge.tool.http;

import com.ruge.tool.json.JsonTool;
import com.ruge.tool.str.StringTool;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Test;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * description:
 *
 * @author alice.ruge
 * date 2022/5/26 9:15
 * @since 0.0.1
 */
@Slf4j
public class HttpToolTest2 {
    /**
     * 您应用的AppKey
     */
    public static final String client_id = "lZEEigCrNs17q3jcK3lGltySoLoWvIsc";
    /**
     * 您应用的授权回调地址
     */
    public static final String redirect_uri = "oob";
    /**
     * 您应用的AppID
     */
    public static final String device_id = "25778676";
    /**
     * 您应用的SecretKey
     */
    public static final String client_secret = "638aDKkimEqGP85Vza0t72kG78O9vHlA";
    /**
     * 用户授权码 Code 值
     */
    public static final String code = "1c897e725fd8d13c1a3d31d9886e5f54";

    @Test
    public void test2() {
        String simpleTokenByCode = getSimpleTokenByCode("");
        System.out.println(simpleTokenByCode);

    }

    /**
     * 授权码模式
     * https://pan.baidu.com/union/doc/al0rwqzzl
     */
    @Test
    public void getAuthUrl() {
        // 发起授权码Code请求
        String url = "http://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&scope=basic,netdisk&device_id=" + device_id;
        System.out.println(url);
        String token = HttpExplorer.builder().build().get(url).getData().toString();
        System.out.println(token);
    }

    /**
     * 简化模式授权
     *
     * @param code
     * @return
     */
    public String getSimpleTokenByCode(String code) {
        String url = "http://openapi.baidu.com/oauth/2.0/authorize?response_type=token&client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&scope=basic,netdisk";
        System.out.println(url);
        String token = HttpExplorer.builder().build().get(url).getData().toString();
        return token;
    }


    public Map<String, Object> getTokenByCode(String code) {
        Map<String, String> map = new HashMap<>();
        String url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=authorization_code&code=" + code + "&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + redirect_uri;
        String token = HttpExplorer.builder().build().get(url).getData().toString();
        String access_token = (String) JsonTool.getJsonToMap(token).get("access_token");
        if (StringTool.isBlank(access_token)) {
            url = "http://openapi.baidu.com/oauth/2.0/authorize?response_type=code&client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&scope=basic,netdisk&device_id=" + device_id;
            System.out.println("重新获取授权页面:" + url);

        }
        map.put("access_token", (String) JsonTool.getJsonToMap(token).get("access_token"));
        map.put("refresh_token", (String) JsonTool.getJsonToMap(token).get("refresh_token"));
        return JsonTool.getJsonToMap(token);
    }


    /**
     * 刷新token
     *
     * @param token
     * @return
     */
    public String refreshToken(String token) {
        String url = "https://openapi.baidu.com/oauth/2.0/token?grant_type=refresh_token&refresh_token=" + token + "&client_id=" + client_id + "&client_secret=" + client_secret;
        String result = HttpExplorer.builder().build().get(url).getData().toString();
        log.info("url:{},rsult:{}", url, result);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return (String) JsonTool.getJsonToMap(result).get("access_token");
    }

    /**
     * 获取用户信息
     */
    @Test
    public void getUserInfo() {
        String token = (String) getTokenByCode("038332f286c97c26a950f02a3ad70cae").get("access_token");
        String url = "https://pan.baidu.com/rest/2.0/xpan/nas?method=uinfo&access_token=" + token;
        System.out.println(url);
        String info = HttpExplorer.builder().build().get(url).getData().toString();
        System.out.println(info);
    }

    /**
     * 递归获取文件列表
     */
    public List<Object> getFileListAll(String token, String dir) throws UnsupportedEncodingException {
        dir = URLEncoder.encode(dir, String.valueOf(StandardCharsets.UTF_8));
        String url = "https://pan.baidu.com/rest/2.0/xpan/file?method=list&access_token=" + token + "&dir=" + dir;
        String info = HttpExplorer.builder().build().get(url).getData().toString();
        Object list = JsonTool.getJsonToMap(info).get("list");
        List<Object> path = JsonTool.getObjToMaps(list).stream().map(e -> e.get("path")).collect(Collectors.toList());
        return path;
    }

    /**
     * 获取文件列表
     */
    public List<Object> getFileList(String token, String dir) throws UnsupportedEncodingException {
        dir = URLEncoder.encode(dir, String.valueOf(StandardCharsets.UTF_8));
        String url = "https://pan.baidu.com/rest/2.0/xpan/file?method=list&access_token=" + token + "&dir=" + dir;
        String info = HttpExplorer.builder().build().get(url).getData().toString();
        Object list = JsonTool.getJsonToMap(info).get("list");
        List<Object> path = JsonTool.getObjToMaps(list).stream().map(e -> e.get("path")).collect(Collectors.toList());
        return path;
    }

    @Test
    public void list() throws UnsupportedEncodingException {
        // 登录
        Map<String, Object> tokens = getTokenByCode("67873dc5dab40b24c3ece2751824015c");
        String token = (String) tokens.get("access_token");
        String refresh_token = (String) tokens.get("refresh_token");
        List<Object> fileList = getFileList(token, "/项目");
        for (int i = 39; i < fileList.size(); i++) {
            List<Object> list = getFileList(refreshToken(refresh_token), (String) fileList.get(i));
            list.forEach(System.out::println);
        }
    }
}
